package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.constant.Constant;
import com.demo.entity.Role;
import com.demo.entity.User;
import com.demo.enums.UserWorkStatusEnum;
import com.demo.jwt.JwtTokenUtil;
import com.demo.mapper.UserMapper;
import com.demo.response.Result;
import com.demo.service.IRoleService;
import com.demo.service.LoginUserService;
import com.demo.util.HeatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.DeploymentException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录
 *
 * @Time 2020-11-24
 */
@Service
public class LoginUserServiceImp implements LoginUserService {
    @Resource
    UserMapper userMapper;
    @Autowired
    IRoleService roleService;

    /**
     * 用户登录
     *
     * @param userLoginName 登录账号
     * @param userPass      登录密码
     * @param workStatus    上班状态：1正常  2值班  3隐身
     * @return
     * @throws NoSuchAlgorithmException
     */
    @Override
    public Result userLogin(String userLoginName, String userPass, Integer workStatus) throws NoSuchAlgorithmException, URISyntaxException, IOException, DeploymentException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_login_name", userLoginName);
        queryWrapper.eq("user_pass", HeatUtil.md5(userPass));
        queryWrapper.isNull("deleted_user_id");
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.error(Constant.USER_NULL);
        }
        //更新用户状态信息
        user.setWorkStatus(workStatus);
        userMapper.updateById(user);

        //获取该用户的所有权限
        Integer roleId = user.getRoleId();
        Role role = roleService.getRoleAll(roleId);
        String action = role.getRoleActions();
        String token = JwtTokenUtil.createAdminToken(user, action);
        Map<String, Object> userInfo = new HashMap<>();

        userInfo.put("token", token);
        userInfo.put("userInfo", user);

        return Result.success(userInfo);
    }

    @Override
    public Result userLoginOut() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        Integer uid = JwtTokenUtil.decodeTokenUserId(request.getHeader("token"));
        User user = new User();
        user.setUserId(uid);
        user.setWorkStatus(UserWorkStatusEnum.YIN_SHEN.getValue());
        userMapper.updateById(user);
        return Result.success();
    }

}
